/**
 * 
 */
package com.lanswon.qzsmk.service.appManageService.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanswon.qzsmk.base.AccountContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.dao.AppClassificationMapper;
import com.lanswon.qzsmk.dao.AppKindMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.SubaccountPersonalMapper;
import com.lanswon.qzsmk.dao.TransGlideMapper;
import com.lanswon.qzsmk.dao.TxnHisDtlMapper;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.AppClassification;
import com.lanswon.qzsmk.model.AppKind;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.SubaccountPersonal;
import com.lanswon.qzsmk.model.TransGlide;
import com.lanswon.qzsmk.model.TxnHisDtl;
import com.lanswon.qzsmk.service.appManageService.BalanceTransfService;
import com.lanswon.qzsmk.vo.AppAcVo;
import com.lanswon.qzsmk.vo.BalanceTransfVo;
import com.lanswon.qzsmk.vo.BalanceVo;

/**
 * @author sun
 *
 */
@Service
public class BalanceTransfServiceImpl implements BalanceTransfService {

	@Autowired
	CardDataMapper cdm;

	@Autowired
	CardControlMapper ccm;

	@Autowired
	SubaccountPersonalMapper spm;

	@Autowired
	AppKindMapper akm;

	@Autowired
	TransGlideMapper tgm;

	@Autowired
	TxnHisDtlMapper thdm;

	@Autowired
	AppClassificationMapper acm;

	@Override
	public BalanceTransfVo showBaseInfo_is_new(BalanceTransfVo vo) {
		BalanceTransfVo vv = new BalanceTransfVo();

//		if (CardContants.CARD_IS_READ.equals(vo.getIsRead())) {// 卡可读的情况,查询新卡账户信息
			CardData cd = cdm.queryCardDataByCitizenCardNo(vo.getNewCitizenCardNo());
			CardControl cc = ccm.queryCardControlByCardDataId(cd.getCardDataId());
			String oldCitizenCardNo = cd.getChcOriCitizenNo();// 旧卡号
			
			// 补/换卡日期
			Date date = cc.getChangeCardDate();
			if (date == null) {
				date = cc.getSupplementCardDate();
			}
			vv.setNewCitizenCardNo(vo.getNewCitizenCardNo());
			vv.setDate(date);
			vv.setOldCitizenCardNo(oldCitizenCardNo);
			
			Map<String, List<BalanceVo>> map = new HashMap<>();

			// 新卡
			List<BalanceVo> l = new ArrayList<>();
			List<SubaccountPersonal> ls = spm.querySubaccountPersonalByCitizenCardNo(vo.getNewCitizenCardNo());

			for (SubaccountPersonal sp : ls) {
				BalanceVo bv = new BalanceVo();
				AppKind ak = akm.queryAppKindByAppFalg(sp.getAppFlag());
				AppClassification ac = acm.queryAppClassificationByAppKindId(ak.getAppKindId());
				bv.setAppFlag(ak.getAppFlag());
				bv.setAppKindName(ac.getAppKindName());
				bv.setAppName(ak.getAppName());
				bv.setCrdBalance(sp.getCrdBalance());
				bv.setCurrCount(sp.getCurrCount() + 1);
				bv.setTotalBalance(sp.getTotalBalance());
				bv.setWalletTypeName(sp.getAcType());

				l.add(bv);
			}
			map.put("newCard", l);
			
			vv.setMap(map);
			
			
		return vv;
	}

	@Override
	public BalanceTransfVo showBaseInfo_is_old(BalanceTransfVo vo) {
		BalanceTransfVo vv = new BalanceTransfVo();

//		if (CardContants.CARD_IS_READ.equals(vo.getIsRead())) {// 卡可读的情况,查询旧卡账户信息
//
//		}
		Map<String, List<BalanceVo>> map = new HashMap<>();

		List<SubaccountPersonal> lsp = spm.querySubaccountPersonalByCitizenCardNo(vo.getOldCitizenCardNo());
		List<BalanceVo> ll = new ArrayList<>();

		for (SubaccountPersonal sp : lsp) {
			BalanceVo bv = new BalanceVo();
			AppKind ak = akm.queryAppKindByAppFalg(sp.getAppFlag());
			AppClassification ac = acm.queryAppClassificationByAppKindId(ak.getAppKindId());
			bv.setAppFlag(ak.getAppFlag());

			bv.setAppKindName(ac.getAppKindName());
			bv.setAppName(ak.getAppName());
			bv.setCrdBalance(sp.getCrdBalance());
			bv.setCurrCount(sp.getCurrCount() + 1);
			bv.setTotalBalance(sp.getTotalBalance());
			bv.setWalletTypeName(sp.getAcType());
			bv.setAppType(ak.getAppType().toString());

			ll.add(bv);
		}
		map.put("oldCard", ll);

		vv.setMap(map);

		return vv;
	}

	@Override
	public BalanceTransfVo showBaseInfo_no(BalanceTransfVo vo) {
		BalanceTransfVo vv = new BalanceTransfVo();

		if (CardContants.CARD_NO_READ.equals(vo.getIsRead())) {// 卡不可读的情况
			vv = showBaseInfo_is_new(vo);
			BalanceTransfVo v1 =showBaseInfo_is_old(vv);
			vv.getMap().put("oldCard", v1.getMap().get("oldCard"));
		}

		return vv;

	}

	@Override
	public void balanceTransf(List<AppAcVo> list, String newCitizenCardNo, String oldCitizenCardNo) {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}		Date now = new Date();

		for (AppAcVo aav : list) {
			AppKind ak = akm.queryAppKindByAppFalg(aav.getAppFlag());

			for (Entry<String, BigDecimal> e : aav.getWalletType_1().entrySet()) {

				SubaccountPersonal sp = spm.querySubaccountPersonalByAppFlagAndWallet(aav.getAppFlag(),
						oldCitizenCardNo, e.getKey());
				sp.setCrdBalance(new BigDecimal(0));// 卡面余额
				sp.setTotalBalance(new BigDecimal(0));// 账面余额
				sp.setTotalConsumeAmt(sp.getTotalConsumeAmt().add(e.getValue()));
				sp.setTotalConsumeCnt(sp.getTotalConsumeCnt() + 1);
				spm.update(sp);

				// 当日交易明细
				TransGlide tg = new TransGlide();
				tg.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
				tg.setAccountType(e.getKey());// 账户类型
				// tg.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
				tg.setAppFlag(aav.getAppFlag());// 应用标识
				tg.setAppType(ak.getAppType().toString());// 应用类型
				tg.setBranchNo(activeUser.getBranchNo());
				// tg.setBusinessNo(businessNo);//业务流水号
				tg.setCitizenCardNo(oldCitizenCardNo);// 市民卡号
				tg.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
				// tg.setFeeRuleId(feeRuleId);//卡费用规则ID
				// tg.setFeeRulesId(feeRulesId);//卡费用细则ID
				tg.setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);// 费用类型
				tg.setIsReturned(AccountContants.STATUS_INVALID);// 是否已退费
				tg.setOprNo(activeUser.getUserNo().toString());
				tg.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);// 现金

				tg.setPaymentTypeExt(AccountContants.STATUS_INVALID);
				// tg.setRptDate(rptDate);//轧帐日期
				tg.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
				// tg.setSubaccountNo(subaccountNo);//网点子账号
				// tg.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
				tg.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
				tg.setTxnAmt(e.getValue());// 交易金额
				tg.setTxnDt(now);// 交易时间
				tg.setTxnTp(AccountContants.TXNTP_CONSUMPTION);// txnTp 交易类型

				tgm.insert(tg);
				Calendar cal = Calendar.getInstance();

				// 转到新卡

				SubaccountPersonal sp_1 = spm.querySubaccountPersonalByAppFlagAndWallet(aav.getAppFlag(),
						newCitizenCardNo, e.getKey());
				sp_1.setCrdBalance(sp_1.getCrdBalance().add(e.getValue()));
				sp_1.setTotalBalance(sp_1.getTotalBalance().add(e.getValue()));
				sp_1.setCurrCount(sp_1.getCurrCount() + 1);
				sp_1.setTotalExchangeCnt(sp_1.getTotalExchangeCnt() + 1);
				sp_1.setTotalExchangeAmt(sp_1.getTotalExchangeAmt().add(e.getValue()));

				spm.update(sp_1);

				// 当日交易明细
				TransGlide tg_1 = new TransGlide();
				tg_1.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
				tg_1.setAccountType(e.getKey());// 账户类型
				// tg_1.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
				tg_1.setAppFlag(aav.getAppFlag());// 应用标识
				tg_1.setAppType(ak.getAppType().toString());// 应用类型
				tg_1.setBranchNo(activeUser.getBranchNo());
				// tg_1.setBusinessNo(businessNo);//业务流水号
				tg_1.setCitizenCardNo(oldCitizenCardNo);// 市民卡号
				tg_1.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
				// tg_1.setFeeRuleId(feeRuleId);//卡费用规则ID
				// tg_1.setFeeRulesId(feeRulesId);//卡费用细则ID
				tg_1.setFeeTp(AccountContants.FEE_TYPE_PRINCIPAL);// 费用类型
				tg_1.setIsReturned(AccountContants.STATUS_INVALID);// 是否已退费
				tg_1.setOprNo(activeUser.getUserNo().toString());
				tg_1.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);// 现金
				tg_1.setPaymentTypeExt(AccountContants.STATUS_INVALID);
				// tg_1.setRptDate(rptDate);//轧帐日期
				tg_1.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
				// tg_1.setSubaccountNo(subaccountNo);//网点子账号
				// tg_1.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
				tg_1.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
				tg_1.setTxnAmt(e.getValue());// 交易金额
				tg_1.setTxnDt(now);// 交易时间
				tg_1.setTxnTp(AccountContants.TXNTP_CONSUMPTION);// txnTp 交易类型
				tgm.insert(tg);

				
			}

		}

	}

	@Override
	public boolean checkCard_1(String citizenCardNo) {
		CardData cd = cdm.queryCardDataByCitizenCardNo(citizenCardNo);
		if (cd != null && StringUtils.isNotEmpty(cd.getChcOriCitizenNo())) {
			return true;
		}
		return false;
	}

	@Override
	public boolean checkCard_2(String newCitizenCardNo, String oldCitizenCardNo) {
		CardData cd = cdm.queryCardDataByCitizenCardNo(newCitizenCardNo);
		if (cd.getChcOriCitizenNo().equals(oldCitizenCardNo)) {
			return true;
		}
		return false;
	}

}
